﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO; 



/// <summary>
///AppSerialize 的摘要说明
/// </summary>
public class AppSerialize {
    public AppSerialize() {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }
    public static MemoryStream Serialize(object obj) {
        BinaryFormatter formatter = new BinaryFormatter();
        MemoryStream ms = new MemoryStream();
        formatter.Serialize(ms, obj);
        return ms;
    }

    public static Stream Serialize(object obj, Stream stream) {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, obj);
        return stream;
    }

    public static object Deserialize(Stream stream) {
        BinaryFormatter formatter = new BinaryFormatter();
        return formatter.Deserialize(stream);
    }

    public static string SerializeToString(object obj) {
        //MemoryStream msObj = Serialize(obj);
        //return Convert.ToBase64String(msObj.ToArray());
        using (MemoryStream ms = new MemoryStream()) {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            return Convert.ToBase64String(ms.ToArray());
        }
    }

    public static object DeserializeFromString(string str) {
        byte[] byteArrayObj = Convert.FromBase64String(str);
        using (Stream myObj = new MemoryStream(byteArrayObj)) {
            BinaryFormatter formatter = new BinaryFormatter();
            return formatter.Deserialize(myObj);
        }
    }   

}
